package com.zhaoyang.util;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @author 赵扬
 * @time 2020/5/6 22:26
 */
public class SHAUtil {
    /**
     * SHA加密密码
     * @param source 需要加密的字符串
     * @return 密文
     */
    public static String encode(String source) {
        StringBuffer hexValue = new StringBuffer();
        try {
            // 获取SHA的消息摘要
            MessageDigest messageDigest = MessageDigest.getInstance("SHA");
            // 获取指定编码的字符串字节数组
            byte[] sourceBytes = source.getBytes("UTF-8");
            // 对指定字节数据进行更新
            byte[] digestBytes = messageDigest.digest(sourceBytes);
            for (int i = 0; i < digestBytes.length; i++) {
                int val = (digestBytes[i] & 0xff);
                if (val < 16) {
                    hexValue.append("0");
                }
                hexValue.append(Integer.toHexString(val));
            }
        } catch (NoSuchAlgorithmException e) {
            return null;// 获取SHA的消息摘要异常
        } catch (UnsupportedEncodingException e) {
            return null;// 获取指定编码的字符串字节数组失败
        } finally {
            return hexValue.toString();
        }
    }
}
